<template>
    <h1>向用户回答吧！</h1>

<input type="text" v-model="question">
<input type="submit" @click="submitQuestion">提交</input>





<div class="page" >

 
<div class="user_list">

<div v-for="(item,index) in user_list" :key="index"  style="margin: 20px;">
    <button @click="checkuser(item)">{{item}}</button>
</div>


</div>

<div class="toby">

{{ message }}


</div>





</div>










</template>





<script setup>
import { ref,onMounted } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()

const server_id = String(route.query.server_id)


const question = ref('')

const user_list = ref([])




const socket = ref(null)


const UserId = ref(null)


const message = ref({})








const initwesockt=()=>{
    socket.value = new WebSocket(`ws://127.0.0.1:8000/webs/${server_id}/`);

    // 当客户端和服务端刚创建好连接(self.accept)之后，自动触发.
    socket.value.onopen =  (event)=>{
        console.log("连接成功")
    }

    // 回调函数，客户端接收服务端消息
    socket.value.onmessage =  (event)=>{
        console.log("收到消息",event)
        if (user_list.value.indexOf(JSON.parse(event.data)['user_id']) == -1){
            let id = JSON.parse(event.data)['user_id'];
            user_list.value.push(id);
            message.value[id] = []
            message.value[id].push(JSON.parse(event.data)['msg'])

        }
        else{
            message.value[JSON.parse(event.data)['user_id']].push("用户输入"+JSON.parse(event.data)['msg'])
        }
        
    


        // list1.value.push(JSON.parse(event.data))
    }

    // // 当断开连接时，触发该函数
    // this.socket.onclose =function (event){
    // let tag = document.createElement("div");
    // tag.innerText = "[连接断开]";
    // document.getElementById("message").appendChild(tag);
    // }

}


onMounted(()=>{
    initwesockt()
})



const submitQuestion = () => {
    if (UserId.value == null){
        alert("请选择用户")
        return
    }
    socket.value.send(JSON.stringify({"user_id":UserId.value,"msg":question.value,"type":"server"}))
    message.value[UserId.value].push("客服输入"+question.value)

    

    
}

const checkuser = (id) => {
    UserId.value = String(id)

    

    
}





</script>




<style scoped>

.page{
    display: flex;

    
}


.toby{
    margin-left: 500px;
    width: 700px;
    background-color: azure;
    height: 1000px;
}




</style>